package com.yishan.gulimall.springsecurity.filter;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yishan.gulimall.springsecurity.domain.LoginUser;
import com.yishan.gulimall.springsecurity.domain.User;
import com.yishan.gulimall.springsecurity.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

@Service
//实现了spring security的UserDetailsService接口
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, s));
        if (ObjectUtils.isEmpty(user)){
            throw new UsernameNotFoundException(s+"不存在");
        }
        List<String> permissionsByUserId = userMapper.findPermissionsByUserId(user.getId());
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);
        loginUser.setPermissions(permissionsByUserId);
        return loginUser;
    }
}
